<?php

namespace App\Admin\Forms\User;

use App\Models\User;
use App\Models\UserTree;
use App\Services\Base\HelpService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class UserMigrationForm extends Form implements LazyRenderable
{
    use LazyWidget;


    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $commit = false;
        //rid 推荐人 new_uid新推荐人 uid当前用户
        try {
            if ($input['rid'] == $input['new_uid']) {
                return $this->response()->error("推荐人和迁移目标不能一样");
            }

            /**
             * @var $user User
             */
            $user = User::query()->where('id', $input['uid'])->first();
//            if ($user->admin_id > 0) {
//                return $this->response()->error("当前账户是代理无法迁移");
//            }

            /**
             * @var $invite_user User
             */
            $invite_user = User::query()->where('id', $input['new_uid'])->first();
            if ($invite_user->admin_id == 0) {
                return $this->response()->error("目标账户不是代理无法迁移");
            }

            $team = $team_before = UserTree::query()->where('pid', $input['uid'])->orderBy('distance', 'asc')->pluck('uid')->toArray();
            array_unshift($team, $input['uid']);
            if (in_array($input['new_uid'], $team)) {
                return $this->response()->error("上级不能为自己的子级");
            }

            $commit = true;
            DB::beginTransaction();

            if ($invite_user->admin_id == 1) {
                $agent_path = 1;
            } else if ($invite_user->admin_id == 0) {
                $agent_path = $invite_user->agent_path;
            } else {
                $agent_path = $invite_user->agent_path . "," . $invite_user->admin_id;
            }

            User::query()->where('id', $input['uid'])->update([
                'rid' => $input['new_uid'],
                'agent_path' => $agent_path,
                'agent_referer' => $invite_user->admin_id
            ]);

            User::query()->whereIn('id', $team_before)->update([
                'agent_path' => $user->admin_id == 0 ? $agent_path : ($agent_path . "," . $user->admin_id),
                'agent_referer' => $user->admin_id == 0 ? $invite_user->admin_id : $user->admin_id
            ]);

            UserTree::deleteTree($team);
            foreach ($team as $k => $val) {
                if ($k == 0) {
                    UserTree::buildUserTree($val, $input['new_uid']);
                } else {
                    UserTree::buildUserTree($val, $team[$k - 1]);
                }
            }
            DB::commit();
            $op_result = true;
        } catch (\Exception $e) {
            HelpService::forceLog($e);
            $commit && DB::rollBack();
            $op_result = false;
        }

        if ($op_result) {
            return $this
                ->response()
                ->success('执行成功')
                ->refresh();
        } else {
            return $this
                ->response()
                ->error('执行失败');
        }
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        /**
         * @var $user User
         */
        $user = User::query()->where('id', $this->payload['id'])->first();
        $this->display('uid_name', __("当前账户"))->value($user->email . "(" . $user->id . ")");
        if ($user->rid) {
            /**
             * @var $refer_user User
             */
            $refer_user = User::query()->where('id', $user->rid)->first();
            $this->display('rid_name', __("推荐人"))->value($refer_user->email . "(" . $refer_user->id . ")");
        } else {
            $this->display('rid_name', __("推荐人"))->value("无");
        }
        $this->hidden('uid')->value($user->id)->readOnly();
        $this->hidden('rid')->value($user->rid)->readOnly();
        $this->select('new_uid', __("迁移目标用户"))->ajax("/users/search")->required()->help("输入邮箱进行搜索");

    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [
        ];
    }
}
